// pages/game/game-record/game-record.js

const { getRoundInfo, getTimeMarkInfo } = require('../../../business/records')
const { calcPoints } = require('../../../business/calcPoints')
const recordsStore = require('../../../stores/records')

Component({

  /**
   * 组件的属性列表
   */
  properties: {
    record: null,
    currentPlayers: null,
  },

  /**
   * 组件的初始数据
   */
  data: {
    // 场次信息
    roundInfo: '',
    // 立直信息
    reachInfo: '',
    // 结局信息
    resultInfo: '',
    // 得点变化
    changePoints: [],
    // 剩余立直棒数
    stickNum: 0,
  },

  lifetimes: {
    ready() {
      this.setRoundInfo()
      this.setReachInfo()
      this.setResultInfo()
      this.setChangePoints()
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    setRoundInfo() {
      this.setData({
        roundInfo: getRoundInfo(this.data.record)
      })
    },
    setReachInfo() {
      const currentPlayers = this.data.currentPlayers;
      const reachPlayers = this.data.record.reachGamers.map(gamer => {
        return currentPlayers[gamer]
      })
      const reachInfo = reachPlayers.map(player => player?.nickname || '匿名').join('，')
      this.setData({
        reachInfo
      })
    },
    setResultInfo() {
      const { result, winGamer, loseGamer, tingGamers, huMethod } = this.data.record;
      const currentPlayers = this.data.currentPlayers;
      const resultInfos = [];
      if (result === 'hu') {
        const winner = currentPlayers[winGamer]
        const huMethodText = huMethod === 'zimo' ? '自摸' : '荣和'
        resultInfos.push(winner.nickname + huMethodText)
        if (huMethod === 'rong') {
          const loser = currentPlayers[loseGamer]
          resultInfos.push(loser.nickname + '放铳')
        }
        resultInfos.push(getTimeMarkInfo(this.data.record))
      } else if (result === 'liu') {
        resultInfos.push('流局')
        const tingers = tingGamers.map(tingGamer => {
          return currentPlayers[tingGamer]
        })
        if (tingers.length === 0) {
          resultInfos.push('无人听牌')
        } else {
          const tingText = tingers.map(tinger => tinger.nickname).join('、');
          resultInfos.push(tingText + '听牌')
        }
      }
      this.setData({
        resultInfo: resultInfos.join('，')
      })
    },
    setChangePoints() {
      // const playerNums = this.data.currentPlayers.map(player => player.playerNum);
      const { changePoints, stickNum } = calcPoints(this.data.record);
      this.setData({ changePoints, stickNum })
    },
    handleDel() {
      const record = this.data.record;
      wx.showModal({
        title: '提示',
        content: '确定删除' + this.data.roundInfo + '信息吗？',
        success(res) {
          if (res.confirm) {
            recordsStore.removeCurrentRecord(record)
          }
        }
      })
    },
    handleEdit() {
      wx.navigateTo({
        url: '/pages/round/round?key=' + this.data.record.key,
      })
    }
  }
})